<?php

namespace app\work\controller;

use think\Controller;
//引入微信SDK
use EasyWeChat\Factory;


class Business extends Controller
{
    public function _initialize()
    {
        // 继承父类
        parent::_initialize();
        $this->BusinessModel = model('Business.Business');
        $this->SourceModel = model('Business.Source');
        $this->OrderProductModel = model('Product.OrderProduct');
        $this->OrderProductModel = model('Product.OrderProduct');

        // 全局配置的微信的SDK填写自己的小程序配置
        $config = [
            'app_id' => 'wx1a5edbe5cfb14e01',
            'secret' => '2b5a2b94eb208f2af0f5197ac0d9e0b9',
            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        //微信小程序SDK实例对象
        $this->app = Factory::miniProgram($config);
    }

    // 微信授权登陆
    public function WxLogin()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code', '', 'trim');

            if(!$code)
            {
                $this->error('临时凭为不能为空');
                exit;
            }
            //请求微信公众平台 换取openid 唯一标识符
            $wxauth =  $this->app->auth->session($code);

            //获取openid 
            $openid = isset($wxauth['openid']) ? $wxauth['openid'] : '';

            if (empty($openid))
            {
                $this->error('授权openid失败');
                exit;
            }

            //查找 openid 绑定的记录
            $BusinessInfo = $this->BusinessModel->where('openid', $openid)->find();

            if($BusinessInfo)
            {
                //有绑定的账号
                $this->success('授权登陆成功', '', $BusinessInfo);
            }
            else
            {
                $this->success('授权成功请绑定账号', '', ['action' => 'bind', 'openid' => $openid]);
                exit;
            }

        }
    }

    // 微信授权绑定账号
    public function WxBind()
    {
        if($this->request->isPost())
        {
            $openid = $this->request->param('openid', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $password = $this->request->param('password', '', 'trim');

            if(empty($openid))
            {
                $this->error('openid不能为空');
                exit;
            }

            if(empty($mobile))
            {
                $this->error('手机号码不能为空');
                exit;
            }

            if(empty($password))
            {
                $this->error('密码不能为空');
                exit;
            }

            $BusinessInfo = $this->BusinessModel->where('mobile', $mobile)->find();

            // 直接绑定帐号
            if($BusinessInfo)
            {
                $password = md5($password . $BusinessInfo['salt']);

                if($password != $BusinessInfo['password'])
                {
                    $this->error('密码错误');
                    exit;
                }

                $result = $this->BusinessModel->where('id', $BusinessInfo['id'])->update(['openid' => $openid]);

                if($result === false)
                {
                    $this->error('绑定账号失败');
                    exit;
                }
                else
                {
                    $BusinessInfo = $this->BusinessModel->find($BusinessInfo['id']);

                    $this->success('绑定成功', '', $BusinessInfo);
                    exit;
                }
            }
            //没有找到用户，意味着 他在其他的平台上没有账号，首次来到小程序
            // Insert 插入语句 顺带将openid 也一并插入进去
            else
            {
                $salt = build_randstr();

                $password = md5($password . $salt);

                $data = [
                    'mobile' => $mobile,
                    'nickname' => $mobile,
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0',
                    'openid' => $openid,
                    'auth' => '0'
                ];

                // 查询某个字段的值
                $sourceid = $this->SourceModel->where('name', 'like', '%防伪查询%')->value('id');
                
                $data['sourceid'] = $sourceid;


                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if ($result === false)
                {
                    $this->error($this->BusinessModel->getError());
                    exit;
                }
                else
                {
                    // 通过自增ID获取刚注册的客户信息
                    $Business = $this->BusinessModel->find($this->BusinessModel->id);

                    $this->success('注册绑定成功', '', $Business);
                    exit;
                }
            }
        }
    }

    // H5或者APP登陆的方法
    public function WebLogin()
    {
        if($this->request->isPost())
        {
            $mobile = $this->request->param('mobile', '','trim');
            $password = $this->request->param('password', '','trim');

            $BusinessInfo = $this->BusinessModel->where('mobile', $mobile)->find();

            // 有帐号，直接登陆
            if($BusinessInfo)
            {
                $password = md5($password . $BusinessInfo['salt']);

                if($password != $BusinessInfo['password'])
                {
                    $this->error('密码错误');
                    exit;
                }

                $this->success('登陆成功', '', $BusinessInfo);
                exit;

            }
            // 注册
            else
            {
                $salt = build_randstr();

                $password = md5($password . $salt);

                $data = [
                    'mobile' => $mobile,
                    'nickname' => $mobile,
                    'password' => $password,
                    'salt' => $salt,
                    'gender' => '0',
                    'auth' => '0'
                ];

                // 查询某个字段的值
                $sourceid = $this->SourceModel->where('name', 'like', '%防伪查询%')->value('id');
                
                $data['sourceid'] = $sourceid;


                $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

                if ($result === false)
                {
                    $this->error($this->BusinessModel->getError());
                    exit;
                }
                else
                {
                    // 通过自增ID获取刚注册的客户信息
                    $Business = $this->BusinessModel->find($this->BusinessModel->id);

                    $this->success('注册成功', '', $Business);
                    exit;
                }
            }
        }
    }

    // 解除绑定账号的方法
    public function unbind()
    {
        if($this->request->isPost())
        {
            $mobile = $this->request->param('mobile', '','trim');
            $id = $this->request->param('id', 0,'trim');

            $BusinessInfo = $this->BusinessModel->where(['mobile' => $mobile, 'id' => $id])->find();

            if(!$BusinessInfo)
            {
                $this->error('用户不存在');
                exit;
            }

            $result = $this->BusinessModel->where('id', $id)->update(['openid' => null]);

            if($result === false)
            {
                $this->error('解除绑定失败');
                exit;
            }
            else
            {
                $this->success('解除绑定成功');
                exit;
            }
        }
    }

    // 防伪列表
    public function ProductIndex()
    {
        if($this->request->isPost())
        {
            $busid = $this->request->param('busid', 0,'trim');
            $page = $this->request->param('page', 1,'trim');
            $keyword = $this->request->param('keyword', '','trim');

            $BusinessInfo = $this->BusinessModel->find($busid);

            if(!$BusinessInfo)
            {
                $this->error('用户不存在');
                exit;
            }

            $where = [
                'busid' => $busid,
            ];

            if(!empty($keyword))
            {
                $where['name'] = ['like', "%$keyword%"];
            }

            $data = $this->OrderProductModel->with('product')->where($where)->order('id desc')->page($page,10)->select();

            if ($data)
            {
                $this->success('返回列表', null, $data);
                exit;
            }
            else
            {
                $this->error('暂无数据');
                exit;
            }
        }
    }

    // 防伪详情
    public function ProductInfo()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code', '','trim');

            $ProductDetails = $this->OrderProductModel->with('product')->where('query_code', $code)->find();

            if (!$ProductDetails)
            {
                $this->error('未查询到防伪码数据');
                exit;
            }

            // 查询一次，次数增加
            $query_num = bcadd($ProductDetails['query_num'], 1);

            $data = [
                'id' => $ProductDetails['id'],
                'query_num' => $query_num,
            ];

            if(empty($ProductDetails['query_num']))
            {
                $data['query_time'] = time();
            }

            $result = $this->OrderProductModel->isUpdate(true)->save($data);

            if($result === false)
            {
                $this->error('更新查询次数错误');
                exit;
            }

            $ProductDetails = $this->OrderProductModel->with('product')->where(['query_code' => $code])->find();

            $this->success('查询防伪码成功', null, $ProductDetails);
            exit;
        }
    }

    // 防伪码
    public function GenerateCode()
    {
        if($this->request->isPost())
        {
            $code = $this->request->param('code', '','trim');

            $ProductDetails = $this->OrderProductModel->with('product')->where('query_code', $code)->find();

            if (!$ProductDetails)
            {
                $this->error('未查询到防伪码数据');
                exit;
            }

            $data = ['id' => $ProductDetails['id'],];

            // 二维码扫描跳转地址
            $url = "/pages/validate/info?code=$code";

            // 返回生成小程序码的一个文件的二进制流
            $response = $this->app->app_code->get($url);

            //调用EasyWechat实例对象(小程序) 来生成小程序码  保存小程序码到文件
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {

                $filename = $response->saveAs('./uploads/qrcode/', "$code.png");

                if(!$filename)
                {
                    $this->error('生成防伪码失败');
                    exit;
                }

                $data['query_qrcode'] = "/uploads/qrcode/$filename";
            }

            $result = $this->OrderProductModel->isUpdate(true)->save($data);
            
            if ($result === false)
            {
                $this->error('更换防伪码失败');
                exit;
            }

            $ProductDetails = $this->OrderProductModel->with('product')->where(['query_code' => $code])->find();

            $this->success('更换防伪码成功', null, $ProductDetails);
            exit;
        }
    }
}
